package com.snj.test;

import java.util.Arrays;
import java.util.List;

public class WeightedAllocator {

    // Test 类的定义
    public static class Test {
        private String name;
        private int num;
        private int total;

        // 构造函数
        public Test(String name, int num, int total) {
            this.name = name;
            this.num = num;
            this.total = total;
        }

        // Getter 和 Setter
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }
    }

    // 分配 total 值的函数
    public static void allocateTotal(List<Test> tests, int total) {
        // 计算 num 的总和
        int totalNum = tests.stream().mapToInt(Test::getNum).sum();

        // 用于存储每个对象分配的 total 值
        int remainingTotal = total;

        // 分配 total 值
        for (Test test : tests) {
            double ratio = (double) test.getNum() / totalNum;
            int allocatedValue = (int) Math.round(ratio * remainingTotal);
            test.setTotal(allocatedValue);
            remainingTotal -= allocatedValue;

            // 如果剩余总值为负，则调整最后一个对象的值以保证总值精确
            if (remainingTotal < 0) {
                test.setTotal(test.getTotal() + remainingTotal);
                remainingTotal = 0;
            }

            // 如果已经分配完毕，退出循环
            if (remainingTotal <= 0) {
                break;
            }
        }

        // 确保总值未超分配，通常在循环中最后的检查已足够
        if (remainingTotal > 0) {
            // 如果还有剩余的 total 值未分配，按照最后一个对象来补充
            Test lastTest = tests.get(tests.size() - 1);
            lastTest.setTotal(lastTest.getTotal() + remainingTotal);
        }
    }

    public static void main(String[] args) {
        // 示例数据
        List<Test> tests = Arrays.asList(
                new Test("Alice", 50, 0),
                new Test("Bob", 30, 0),
                new Test("Charlie", 100, 0)
        );

        int total = 500;

        // 调用分配方法
        allocateTotal(tests, total);

        // 输出结果
        for (Test test : tests) {
            System.out.println(test.getName() + ": " + test.getTotal());
        }
    }
}